<template>
  <div class="container">
    <div class="header">
      <el-image src="/pic_01.png" fit="contain" class="icon"></el-image>
      <h1 class="title">身份认证</h1>
    </div>
    <el-form
        label-position="top"
        :model="state.form"
        :rules="rules"
        ref="ruleFormRef"
        class="form">
      <el-form-item label="姓名" prop="username">
        <el-input v-model="state.form.username" placeholder="可以填写便于客服识别的艺名" :prefix-icon="Avatar"></el-input>
      </el-form-item>
      <el-form-item label="手机号" prop="mobile">
        <el-input v-model.number="state.form.mobile" placeholder="请输入手机号"  :prefix-icon="PhoneFilled">
        </el-input>
      </el-form-item>
      <el-form-item label="能力" prop="capacity" >
        <el-input v-model="state.form.capacity" placeholder="请输入您的能力（程序员/写手/其他）" :prefix-icon="Star"></el-input>
      </el-form-item>
      <el-button  :disabled="isButtonDisabled" type="primary" size="large" class="submit-button" @click="checkProgress(ruleFormRef)" >点击进行认证</el-button>
      <p class="note">
        <span style="color: red">*</span>认证后客服会找您核验身份。
      </p>
    </el-form>
  </div>
</template>
<script setup lang="ts">
import { useHead } from "#app";
import {useRoute, useRouter} from "vue-router";
import {Avatar, PhoneFilled, Star} from "@element-plus/icons-vue";
import {userStore} from "~/composables/useUserStore";
import requester from "~/utils/request";
import type {FormInstance, FormRules } from 'element-plus'
const router = useRouter()
const store = userStore()
const route = useRoute()
const namePattern = /^[\u4e00-\u9fa5]{2,4}$/;
const rules = reactive<FormRules<any>>({
  username: [{ required: true, message: '请输入您的姓名', trigger: 'blur' },
    { pattern: namePattern, message: '请输入有效的中文姓名（2-4个汉字）', trigger: 'blur' }],
  mobile: [
    { required: true, message: '请输入您的手机号', trigger: 'blur' },
    {
      pattern: /^1[3-9]\d{9}$/,  // 手机号的正则表达式，适用于中国大陆手机号
      message: '请输入有效的手机号',
      trigger: 'blur'
    }
  ],
  capacity: [{ required: true, message: '请输入您的能力', trigger: 'blur' },],
})
const ruleFormRef = ref<FormInstance>()
// 设置页面标题
useHead({
  title: '迅颖身份认证平台',
});

const isButtonDisabled = ref(false);  // 控制按钮的禁用状态

const  state = reactive(<any>{
  form:{
    username:"",
    mobile:"",
    capacity:"",
    userCode:"",
  }
})

/**
 * 初始化项目
 */
const init = () => {
  // 先查询是否登录
  if (store.isLogin) {
    return;
  }
  getCode()
}

onMounted(() =>{
  //初始化
  init()
  silentLogin()
})

// 生产环境
function getCode() {
  //拼接链接进行登录
  window.location.replace(`https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx4754a2bb841ba595&redirect_uri=` +
      encodeURIComponent("https://xunyingcloud.cn/my/mobile/authentication") +
      "&response_type=code&scope=snsapi_userinfo&state=1&connect_redirect=1#wechat_redirect")
}

const silentLogin = async () => {
  const code = route.query.code
  //code换取登录信息
  requester.post('/api/login/codeLogin', {code: code, type: "snsapi_userinfo"}).then((response: any) => {
    //40029code被使用
    //存储用户信息
    console.log("获取用户信息：",response.data)
    state.form.mobile =  store.token.cellPhone
    store.setToken(response.data)
    //设置登录状态
    store.isLogin = true
  })
}
// 认证按钮点击事件
const checkProgress = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid) => {
    if (valid) {
      //获取用户编号
      // 禁用按钮，防止重复点击
      isButtonDisabled.value = true;
      console.log("获取用户信息toekn：", store.token)
      state.form.userCode =  store.token.userCode
      requester.post("/api/login/auth",state.form).then((response:any) =>{
        // 操作完成后，恢复按钮状态
        isButtonDisabled.value = false;
        if (response.code === 200) {
          router.push(`projectAddSuccess`)
        }else {
          ElMessage({
            message: response.msg,
            type: 'error',
          })
        }
      })
    }
  })
}
</script>
<style scoped>
.container {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px;
  background-image: url(/auth-bg.jpg); /* 背景图 */
  min-height: 100vh;
}

.header {
  text-align: center;
  margin-bottom: 20px;
}

.icon {
  width: 100px;
  height: 100px;
  margin-bottom: 10px;
}

.title {
  font-size: 25px;
  color: #ffffff;
  text-align: center;
  font-weight: bold;
  padding: 0.4rem 0;
}

.form {
  width: 100%;
  max-width: 400px;
  background-color: #ffffff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.submit-button {
  width: 100%;
  background-color: #4ea5f1;
  color: white;
  font-weight: bold;
  margin-top: 20px;
}

.note {
  margin-top: 15px;
  font-size: 14px;
  color: #666666;
  text-align: center;
}
</style>
